#include "DynamicStruct.hpp"

DynamicStruct::DynamicStruct()
{}

DynamicStruct::DynamicStruct(std::initializer_list<std::pair<std::string,double>> initList)
{
    for(auto i : initList)
        numMap.insert(i);
}

DynamicStruct::~DynamicStruct()
{}

void DynamicStruct::addKey(std::string Key, double Value)
{
    numMap.insert({Key,Value});
}

void DynamicStruct::addKey(std::string Key, std::string Value)
{
    strMap.insert({Key,Value});
}

bool DynamicStruct::getKey(std::string Key, double& Value)
{
    auto findRes=numMap.find(Key);
    if(findRes==numMap.end())
        return false;
    else
    {
        Value=findRes->second;
        return true;
    }
}

bool DynamicStruct::getKey(std::string Key, std::string& Value)
{
    auto findRes=strMap.find(Key);
    if(findRes==strMap.end())
        return false;
    else
    {
        Value=findRes->second;
        return true;
    }
}

bool DynamicStruct::removeKey(std::string Key)
{
    if(numMap.erase(Key)==1 || strMap.erase(Key)==1)
        return true;
    return false;
}

nlohmann::json DynamicStruct::toJson()
{
    nlohmann::json Res;
    for(std::pair<const std::string,double>& i: numMap)
        Res[i.first]=i.second;
    for(std::pair<const std::string,std::string>& i : strMap)
        Res[i.first]=i.second;
    return Res;
}

std::list<std::string> DynamicStruct::getAllNumKey()
{
    std::list<std::string> Res;
    for(std::pair<const std::string,double>& i : numMap)
        Res.push_back(i.first);
    return Res;
}

void DynamicStruct::cloneNum(const DynamicStruct& scoreObject)
{
    numMap.clear();
    for(const std::pair<const std::string,double>& i : scoreObject.numMap)
        numMap.insert({i.first,0});
}

bool DynamicStruct::setKey(std::string Key,const double Value)
{
    auto FindRes=numMap.find(Key);
    if(FindRes==numMap.end())
        return false;
    FindRes->second=Value;
    return true;
}

bool DynamicStruct::setKey(std::string Key,const std::string& Value)
{
    auto FindRes=strMap.find(Key);
    if(FindRes==strMap.end())
        return false;
    FindRes->second=Value;
    return true;
}

bool DynamicStruct::addNum(const DynamicStruct& scoreObject)
{
    bool isAllSuccess=true;
    for(auto i : scoreObject.numMap)
    {
        auto findRes=numMap.find(i.first);
        if(findRes==numMap.end())
            isAllSuccess=false;
        else
            findRes->second+=i.second;
    }
    return isAllSuccess;
}

void DynamicStruct::divisionNum(double Value)
{
    for(auto& i : numMap)
        i.second/=Value;
}